package com.simon.app.october.modules.sys.controllers;

import com.simon.app.october.common.annotation.SysLog;
import com.simon.app.october.common.utils.Result;
import com.simon.app.october.modules.sys.entity.SysUserEntity;
import com.simon.app.october.modules.sys.form.SysLoginForm;
import com.simon.app.october.modules.sys.service.SysUserService;
import com.simon.app.october.modules.sys.service.SysUserTokenService;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/sys")
public class SysLoginController extends AbstractController {

    @Autowired
    SysUserService sysUserService;

    @Autowired
    SysUserTokenService sysUserTokenService;

    @PostMapping("/login")
    public Map<String, Object> login(@RequestBody SysLoginForm form) {

        SysUserEntity user = sysUserService.findByUsername(form.getUsername());

        if (user == null || !user.getPassword().equals(new Sha256Hash(form.getPassword(), user.getSalt()).toHex())) {
            return Result.error(1, "用户名或密码不正确");
        }

        if (0 == user.getStatus()) {
            return Result.error(2, "账号已被锁定，请联系管理员");
        }

        // 生成token
        String token = sysUserTokenService.createToken(user.getUserId());

        return Result.ok().put("token", token);
    }

    @PostMapping("/logout")
    public Result logout() {
        sysUserTokenService.logout(getUserId());
        return Result.ok();
    }
}
